package tarena.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	private static Configuration cfg = Configuration.configure(); // 加载配置信息

	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

	private static BasicDataSource ds = new BasicDataSource();

	static {
		try {
			// Class.forName(cfg.getDriver());// 注册驱动
			ds.setUrl(cfg.getUrl());
			ds.setDriverClassName(cfg.getDriver());
			ds.setUsername(cfg.getUsername());
			ds.setPassword(cfg.getPassword());

			ds.setInitialSize(cfg.getInitialSize());
			ds.setMaxActive(cfg.getMaxActive());
			ds.setMaxIdle(cfg.getMaxIdle()); // 最大空闲数
			ds.setMaxWait(cfg.getMaxWait());
			ds.setValidationQuery(cfg.getValidationQuery());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Connection open() throws SQLException {
		// return DriverManager.getConnection(
		// cfg.getUrl(),cfg.getUsername(),cfg.getPassword());
		return ds.getConnection();
	}

	public static void close(Connection con, Statement stmt, ResultSet rs) {
		try {
			if (null != rs) {
				rs.close();
			}
		} catch (Exception e) {
		}
		try {
			if (null != stmt) {
				stmt.close();
			}
		} catch (Exception e) {
		}
		try {
			if (null != con) {
				con.close();
			}
		} catch (Exception e) {
		}
	}

	public static Connection openInThread() throws SQLException {
		Connection con = threadLocal.get();
		if (null == con) {
			con = open();
			threadLocal.set(con);
		}
		return con;
	}

	public static void closeInThread() {
		Connection con = threadLocal.get();
		if (null != con) {
			try {
				con.close();
			} catch (Exception e) {
			}
			threadLocal.remove();
		}
	}

	public static void main(String[] args) throws Exception {
		long t = System.currentTimeMillis();

		for (int i = 0; i < 100; i++) {
			Connection con = DBUtil.open();
			DBUtil.close(con, null, null);
		}

		System.out.println(System.currentTimeMillis() - t);
	}
}
